# 姓名:刘豹
#  开发时间: 2021/3/22 22:07
import numpy as np
import cv2 as cv
import os
import matplotlib.pyplot as plt
#中文路径读取
def my_cv_imread(filepath):
    # 使用imdecode函数进行读取
    img = cv.imdecode(np.fromfile(filepath,dtype=np.uint8),-1)
    return img
#实现背景抠图
def koutu(img):
    lower=np.array([20,70,70],dtype = "uint8")
    upper=np.array([100,255,255],dtype = "uint8")
    hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
    mask = cv.inRange(hsv, lower, upper)
    image = cv.bitwise_and(img, img, mask=mask)
    # cv.namedWindow('1',2)
    # cv.imshow('1',image)
    # cv.waitKey(0)
    gray=cv.cvtColor(image,cv.COLOR_BGR2GRAY) #转换为灰度图
    contours, hierarchy = cv.findContours(gray,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)#轮廓检测
    height, width = img.shape[:2]
    index = 0
    max = 0
    for c in range(len(contours)):
        x, y, w, h = cv.boundingRect(contours[c])
        if h>height or w >width:
           continue
        area = cv.contourArea(contours[c])
        if area > max:
           max = area
           index = c
    x, y, w, h = cv.boundingRect(contours[index])
    #print(len(contours))
    #print(index)
    # result = np.zeros(img.shape, dtype=np.uint8)
    # cv.drawContours(result,contours,index,(0,0,255),2)  #绘制轮廓
    # cv.namedWindow("5", 2)#创建一个窗口
    # cv.imshow("5", result)  #显示灰度图
    # result1 = np.zeros(img.shape, dtype=np.uint8)
    # cv.rectangle(result1, (x,y,w,h), (0, 225, 0), 20)  # 绘制矩形
    # cv.namedWindow("6", 2)#创建一个窗口
    # cv.imshow("6", result1)  #显示灰度图
    # cv.waitKey(0)
    cropped = img[y:y+h-50,x:x+w-50]
    # cv.namedWindow("7", 2)#创建一个窗口
    # cv.imshow("7", cropped)  #显示灰度图
    #print(cropped.shape)3100,2400
    dst=cv.resize(cropped,(1000,900),interpolation=cv.INTER_CUBIC)
    #print(dst.shape)
    # cv.namedWindow("8", 2)#创建一个窗口
    # cv.imshow("8", dst)  #显示灰度图
    # cv.waitKey(0)
    return dst
#实现计数功能
def jishu(img):
    grayImage=cv.cvtColor(img,cv.COLOR_BGR2GRAY)
    # grayImage = cv.equalizeHist(grayImage)
    # clahe = cv.createCLAHE(clipLimit=3, tileGridSize=(10, 10))
    # grayImage = clahe.apply(grayImage)
    kernelx=np.array([[1,1,1],[0,0,0],[-1,-1,-1]],dtype=int)  #prewitt 1算子
    kernely=np.array([[-1,0,1],[-1,0,1],[-1,0,1]],dtype=int)  #prewitt 2算子
    x=cv.filter2D(grayImage,cv.CV_16S,kernelx)
    y=cv.filter2D(grayImage,cv.CV_16S,kernely)
    absx=cv.convertScaleAbs(x)
    absy=cv.convertScaleAbs(y)
    Prewitt=cv.addWeighted(absx,0.5,absy,0.5,0)

    cv.namedWindow("9", 2)
    cv.imshow('9',Prewitt)
    cv.waitKey()
    ret,Prewitt = cv.threshold(Prewitt,35,255,cv.THRESH_BINARY) #输入灰度图，输出二值图

    element = cv.getStructuringElement(cv.MORPH_CROSS,(1, 1))#形态学去噪
    Prewitt=cv.morphologyEx(Prewitt,cv.MORPH_OPEN,element)  #开运算去噪
    cv.namedWindow("10", 2)
    cv.imshow('10',Prewitt)
    cv.waitKey(0)
    contours, hierarchy = cv.findContours(Prewitt,cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)
    cv.drawContours(Prewitt,contours,-1,(120,0,0),2)  #绘制轮廓
    #cv.namedWindow("11", 2)   #创建一个窗口
    #cv.imshow("11", Prewitt)  #显示灰度图
    count=0
    for cont in contours:
       ares=cv.contourArea(cont)

       if ares<10 or ares>120:
          continue
       count+=1
       print('标号{}--面积{}:'.format(count,ares),end='')
       x,y,w,h=cv.boundingRect(cont)
       print('坐标为x-{}-y-{}'.format(x,y))
       cv.rectangle(img, (x,y,w,h), (0, 0, 255), 1)  # 绘制矩形
       y = 10 if y < 10 else y
       cv.putText(img,str(count),(x,y),cv.FONT_HERSHEY_COMPLEX,0.4, (0, 255, 0), 1)
    cv.namedWindow('12', 2)
    cv.imshow('12', img)
    cv.waitKey(0)
#循环读取图片文件
# for root, dirs, files in os.walk("/insects_imgs/5-1-1-A.jpg"):
#     for name in files:
#         filepath = (os.path.join(root, name))
img = my_cv_imread('D:\python\workspace\insects_detection\processed_imgs\\5-1-1-B.jpg')
# a=koutu(img)
jishu(img)






